<template>
	<div class="header">
		<span @click="$router.go(-1)"><</span>
		<span>{{ config.name }}</span>
	</div>
	<div
		class="body"
		ref="body"
		:style="{ backgroundImage: `url(${config.backgroundImage})` }">
		<Talk
			:talkList="user[props.config.name]"
			:avatar="config.avatar"></Talk>
	</div>
	<div class="footer">
		<el-row
			class="footer-row"
			:gutter="5">
			<el-col :span="20">
				<el-input
					:autosize="{ minRows: 1, maxRows: 2 }"
					v-model="message"
					:style="{ width: '100%' }"
					:rows="2"
					type="textarea"
					resize="none"
					@keydown.enter.native="send" />
			</el-col>
			<el-col :span="4">
				<el-button
					type="primary"
					@click="send"
					:disabled="blok">
					发送
				</el-button>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
import { useTalkStore } from "@/stores/talk"
import { storeToRefs } from "pinia"
import { getCurrentInstance, ref, nextTick, onMounted } from "vue"
import Talk from "@/components/Talk.vue"

const { proxy } = getCurrentInstance()

const props = defineProps({
	config: {
		type: Object,
		required: true,
	},
})

const body = ref(null)

onMounted(() => {
	// 滚轮滑动到底部
	body.value.scrollTop = body.value.scrollHeight
})

const blok = ref(false)
const message = ref("")

const talkStore = useTalkStore()
const { talkListObj } = storeToRefs(talkStore)

const user = {
	芥川龙之介: talkListObj.value.jiechuanTalkList,
	太宰治: talkListObj.value.taizaiTalkList,
	江户川乱步: talkListObj.value.luanbuTalkList,
}

let saveMessage = ""

const send = () => {
	if (message.value.trim() === "" || blok.value) {
		return
	}

	saveMessage = message.value.trim()
	blok.value = true
	nextTick(() => {
		message.value = ""
	})

	user[props.config.name].push({
		time: new Date().toLocaleString(),
		nameRight: "我",
		nameLeft: props.config.name,
		contentRight: saveMessage,
		contentLeft: "对方正在输入中。。。",
	})

	nextTick(() => {
		body.value.scrollTop = body.value.scrollHeight
	})

	requestMessage()
}

const requestMessage = async () => {
	let result = await proxy.Request({
		url: "/v1/chat/completions",
		message: saveMessage,
		role: props.config.role,
	})
	if (!result) {
		return
	}
	user[props.config.name][user[props.config.name].length - 1].contentLeft = result.choices[0].message.content
	blok.value = false
}
</script>

<style scoped lang="scss">
.header {
	display: flex;
	height: 60px;
	width: 100%;
	background-color: #333;
	justify-content: center;

	span {
		font-size: 20px;
		font-weight: bold;
		color: #fff;
		line-height: 60px;
	}
	span:nth-of-type(1) {
		cursor: pointer;
		height: 0px;
		position: absolute;
		margin-left: 50px;
		left: 0;
	}
}

.body {
	height: calc(100% - 120px);
	width: 100%;
	// 跟着新的内容滚动
	overflow-y: auto;
	background-size: cover;
}

.footer {
	width: 100%;
	height: 60px;
	background-color: #f5f5f5;

	.footer-row {
		padding: 5px 10px;
		align-items: center;
	}
}
</style>
